package com.unittec.drainage.provider.auth.controller;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.unittec.drainage.provider.auth.excel.export.ExcelExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.unittec.drainage.provider.common.BeanValidator;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.utils.StringUtil;
import com.unittec.drainage.provider.utils.ValidationUtils;
import com.unittec.drainage.sdk.auth.request.Req101911;
import com.unittec.drainage.sdk.auth.request.Req101912;
import com.unittec.drainage.sdk.auth.response.Res101911;
import com.unittec.drainage.sdk.auth.response.Res101912;
import com.unittec.drainage.sdk.log.enums.LogOperateEnum;
import com.unittec.drainage.sdk.log.enums.LogStatusEnum;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.enums.BizCode;

import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description:
 * @author: chenjiawang
 * @CreateDate: 2020/6/15 14:03
 */
@RestController
@Api(tags = "EXCEL导出管理")
public class ExcelExportController {

    @Autowired
    private Log log;
    @Autowired
    private ExcelExportService excelExportService;

    @RequestMapping(value = "/101911", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "EXCEL导出", notes = "EXCEL导出")
    public Result<Res101911> exportExcel(@RequestBody GatewayRequest<Req101911> req) {
        log.debug(req, "exportExcel  {},param:{}  ", "begin", JSON.toJSONString(req.getContent()));
        long startLogTime = System.currentTimeMillis();
        try {
            // 参数校验
            BeanValidator.validate(req.getContent());
        } catch (Exception e) {
            log.error(req, "exportExcel  error  end ", e);
            log.addOperateLog("101911", JSON.toJSONString(req.getContent()), "EXCEL导出", "参数错误：" + log.buildErrmsg(e),
                LogOperateEnum.LOG_EXPORT.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, BizCode.PARAM_ERROR.getCode(), e.getMessage());
        }
        String consumer = req.getContent().getConsumer();
        String type = req.getContent().getType();
        boolean async = req.getContent().getAsync() == null ? false : req.getContent().getAsync();

        try {
            Map<String, Object> paramMap =
                req.getContent().getParamMap() == null ? new HashMap<>(16) : req.getContent().getParamMap();
            paramMap.put("type", type);
            Object obj = excelExportService.export(consumer, type, async, paramMap);
            Res101911 res = new Res101911();
            res.setObj(obj);
            log.addOperateLog("101911", JSON.toJSONString(req.getContent()), "EXCEL导出", "操作成功",
                LogOperateEnum.LOG_EXPORT.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            // 返回数据
            log.debug(req, "exportExcel  success  end ");
            return Result.success(req, res);
        } catch (Exception e) {
            log.addOperateLog("101911", JSON.toJSONString(req.getContent()), "EXCEL导出失败", log.buildErrmsg(e),
                LogOperateEnum.LOG_EXPORT.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            // 调用微服务数据保存异常
            log.error(req, BizCode.SAVE_ERROR.getMessage(), e);
            return Result.error(req, BizCode.SAVE_ERROR.getCode(),
                StringUtil.isEmpty(e.getMessage()) ? BizCode.SAVE_ERROR.getMessage() : e.getMessage());
        }

    }

    @RequestMapping(value = "/101912", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "导出字段", notes = "导出字段")
    public Result<Res101912> exportFieldList(@RequestBody GatewayRequest<Req101912> req) {
        try {
            log.debug(req, "exportFieldList  {},param:{}  ", "begin", JSON.toJSONString(req.getContent()));
            // 参数校验
            ValidationUtils.validateEntity(req.getContent());
            Req101912 req101912 = req.getContent();

            String EXPORT_drainage_FIELD = "template/导出资产字段.json";
            String EXPORT_TRANSACTION_FIELD = "template/导出交易字段.json";
            String EXPORT_DATA_COUNT = "template/数据统计导出字段.json";

            // String drainageMsg = StrUtil.toString(this.getClass().getResourceAsStream(EXPORT_drainage_FIELD));
            // String transactionMsg = StrUtil.toString(this.getClass().getResourceAsStream(EXPORT_TRANSACTION_FIELD));
            String drainageMsg = StreamUtils.copyToString(new ClassPathResource(EXPORT_drainage_FIELD).getInputStream(),
                StandardCharsets.UTF_8);
            String transactionMsg = StreamUtils
                .copyToString(new ClassPathResource(EXPORT_TRANSACTION_FIELD).getInputStream(), StandardCharsets.UTF_8);
            String dataCount = StreamUtils.copyToString(new ClassPathResource(EXPORT_DATA_COUNT).getInputStream(),
                StandardCharsets.UTF_8);

            JSON drainageList = (JSON)JSON.parse(drainageMsg);
            JSON transactionList = (JSON)JSON.parse(transactionMsg);
            JSON dataCountList = (JSON)JSON.parse(dataCount);

            Res101912 res = new Res101912();
            Map<String, Object> map = new HashMap<>(16);
            if (ObjectUtil.isNotNull(req101912.getType()) && "1".equals(req101912.getType())) {
                map.put("dataCountList", dataCountList);
            } else {
                map.put("drainageList", drainageList);
                map.put("transactionList", transactionList);
            }
            res.setObj(map);
            // 返回数据
            log.debug(req, "exportFieldList  success  end ");
            return Result.success(req, res);
        } catch (Exception e) {
            log.error(req, BizCode.LIST_ERROR.getMessage(), e);
            return Result.error(req, BizCode.LIST_ERROR.getCode(),
                StringUtil.isEmpty(e.getMessage()) ? BizCode.LIST_ERROR.getMessage() : e.getMessage());
        }
    }

}
